package com.store.controller;

import com.store.common.Result;
import com.store.dto.CategoryRequest;
import com.store.service.CategoryService;
import com.store.vo.CategoryVO;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品分类控制器
 * 
 * @author Store Team
 */
@RestController
@RequestMapping("/category")
@RequiredArgsConstructor
public class CategoryController {

    private final CategoryService categoryService;

    /**
     * 获取分类树
     */
    @GetMapping("/tree")
    public Result<List<CategoryVO>> getCategoryTree() {
        try {
            List<CategoryVO> tree = categoryService.getCategoryTree();
            return Result.success("查询成功", tree);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取分类列表
     */
    @GetMapping("/list")
    public Result<List<CategoryVO>> getCategoryList() {
        try {
            List<CategoryVO> list = categoryService.getCategoryList();
            return Result.success("查询成功", list);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据ID获取分类详情
     */
    @GetMapping("/{id}")
    public Result<CategoryVO> getCategoryById(@PathVariable Long id) {
        try {
            CategoryVO category = categoryService.getCategoryById(id);
            return Result.success("查询成功", category);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 创建分类（管理员权限）
     */
    @PostMapping
    public Result<CategoryVO> createCategory(@Valid @RequestBody CategoryRequest request) {
        try {
            CategoryVO category = categoryService.createCategory(request);
            return Result.success("创建成功", category);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新分类（管理员权限）
     */
    @PutMapping
    public Result<CategoryVO> updateCategory(@Valid @RequestBody CategoryRequest request) {
        try {
            CategoryVO category = categoryService.updateCategory(request);
            return Result.success("更新成功", category);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除分类（管理员权限）
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteCategory(@PathVariable Long id) {
        try {
            categoryService.deleteCategory(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

}







